package com.chao.deeply.aqs;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author : Rookie
 * @description :
 * @date : 2023/8/20
 */
public class PrintThread {

    // 打印次数
    private static final int TOTAL_COUNT = 10;
    // 锁
    private static final Object lock = new Object();
    // 当前线程id
    private static int currentThreadId = 1;

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(new PrintLetter("A",1));
        Thread thread2 = new Thread(new PrintLetter("B",2));
        Thread thread3 = new Thread(new PrintLetter("C",3));

        thread1.start();
        thread2.start();
        thread3.start();
    }

    static class PrintLetter implements Runnable {
        
        private final String letter;

        private final int threadId;
        
        public PrintLetter(String letter,int threadId) {
            this.letter = letter;
            this.threadId = threadId;
        }

        @Override
        public void run() {
            for (int i = 0; i < TOTAL_COUNT; i++) {
                synchronized (lock) {
                    while (currentThreadId != threadId) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("线程" + threadId + "打印了" + letter);
                    currentThreadId = (threadId % 3) +1;
                    lock.notifyAll();
                }
            }
        }
    }
}
